package com.example.everying.service.chat.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.everying.constant.ChatMessageConstant;
import com.example.everying.framework.websocket.service.WebSocketChatService;
import com.example.everying.mapper.system.SysNotificationMapper;
import com.example.everying.model.dto.chat.ConversationDto;
import com.example.everying.model.entity.chat.ChatMessagesEntity;
import com.example.everying.model.entity.system.SysNotification;
import com.example.everying.service.chat.ChatConversationService;
import com.example.everying.service.chat.ChatMessagesService;
import com.example.everying.service.system.SysNotificationService;
import com.example.everying.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@Slf4j
public class RedDotService {

    @Autowired
    private ChatConversationService chatConversationService;
    @Autowired
    private ChatMessagesService chatMessagesService;
    @Autowired
    private SysNotificationMapper sysNotificationService;
    @Autowired
    private UserService userService;

    @Async
    public void sendRedDot(String userId) {
        List<ConversationDto> conversations = chatConversationService.getUserConversationsByRedDot(userId);
        JSONObject result = new JSONObject();
        result.put("type", "navigationRedDotMessage");
        AtomicInteger unreadCount = new AtomicInteger();
        conversations.forEach(conversation -> {
            if (conversation.getUnreadCount() > 0) {
                unreadCount.addAndGet(conversation.getUnreadCount());
            }
        });
        // 评论未读消息数
        int unreadCount2 = Math.toIntExact(chatMessagesService.count(new QueryWrapper<ChatMessagesEntity>().eq("to_user_id", userId).
                eq("msg_status", ChatMessageConstant.MESSAGE_STATUS_UNREAD).eq("messages_type", ChatMessageConstant.MESSAGE_TYPE_ACTIVITY_COMMENT)));
        log.info("评论未读消息数: {}", unreadCount2);
        int num = unreadCount2 + unreadCount.get();
        // 通知未读数
        int num2 = Math.toIntExact(sysNotificationService.selectList(new QueryWrapper<SysNotification>().eq("recipient_id", userId).eq("msg_status", 2)).size());
        // 官方通知的消息
        int num3 = Math.toIntExact(userService.getUserById(userId).getNoticeUnreadCount() == null ? 0 : userService.getUserById(userId).getNoticeUnreadCount());
        result.put("redDotNum", num + num2 + num3);
        WebSocketChatService.sendMessageToUserId(userId, result.toJSONString());
    }
}
